<script setup lang="ts">
import { getCurrentInstance, ref, onMounted } from 'vue'
const { proxy } = getCurrentInstance()

/* ---- */
const userInfo = proxy.$Store.get('userInfo') || {}
const logUser = proxy.$Store.get('logUser') || {}
const WXConfig = proxy.$Store.get('WXConfig') || {}
const forFees = proxy.$Fees || []

/* --设置微信分享功能-- */
proxy.$WxTool.loadJsdk(WXConfig, (obj) => {
  if (!obj) return
  // ----
  obj.hideMenuItem()
})

/* ---- */
const user = {
  title: '感谢支持【万域商友会】',
  logo: proxy.$shareIcon
}
// ----
const forToPay = proxy.$route.query.toPay ? JSON.parse(proxy.$route.query.toPay) : null
const forExtend = proxy.$route.query.exTend ? JSON.parse(proxy.$route.query.exTend) : null
// ----
let deadline = []
// ----
let endtime = null
let deadtime = null
let forDays = 1
// ----
let trueNum = 0
// ----
let amount = 1
let feeNum = 0
let feeGive = 0
// ----
let power = 1

/* ---- */
const layer = ref()

/* ---- */
const getCurrencyInfo = async () => {
  proxy.$Myfun.getJsonData(logUser.topupze, (resJson) => { deadline = resJson })
  // ----
  forFees.some((item) => {
    if (String(item.id) === String(forToPay.payType)) {
      amount = Number(item.amount)
      feeNum = Number(item.num)
      if (item.give && Number(item.give.length) > 0) feeGive = Number(item.give)
    }
  })
  // ----
  if (forToPay.payCount) {
    forDays = Number(forToPay.payCount) * feeNum
    amount = amount * forToPay.payCount
  }
  // ----
  if (forToPay.payAttr) {
    trueNum = Number(logUser[forToPay.payAttr]) || 0
    let forLookNum = feeGive
    if (forToPay.payCount) forLookNum = Number(forToPay.payCount) * feeGive
    trueNum += forLookNum
  }
  // ----
  deadtime = proxy.$Myfun.getNewDate({num: forDays})
  // --判断当前登陆者充值状态--
  if (Number(Object.keys(logUser).length) > 0) {
    power = 2
    // ----
    let amountDate = 0
    deadline.some((oneItem) => {
      if (String(oneItem.id) === String(forToPay.payType)) {
        oneItem.info.some((twoItem) => {
          if (String(twoItem.id) === String(forToPay.payId)) {
            endtime = twoItem.endtime
            amountDate = Date.parse(new Date(twoItem.endtime.replace(/-/g, '/'))) || 0
          }
        })
      }
    })
    const curDate = Date.parse(new Date())
    if (Number(amountDate) >= Number(curDate)) {
      power = 3
      deadtime = proxy.$Myfun.getNewDate({date: endtime})
    }
  }
  // ----
  const forType = 'post'
  const forUrl = 'payment/start'
  const forData = {
    type: forToPay.regType,
    pay_type: forToPay.payType,
    dealer_id: logUser.id,
    // ----
    amount: amount,
    deadline: deadtime,
    // ----
    config_id: userInfo.config_id,
    openid: userInfo.openid
  }
  if (forToPay.payIdKey) forData[forToPay.payIdKey] = forToPay.payId
  // ----
  let resData = ''
  await proxy.$http[forType](forUrl, forData).then((res) => { resData = res }).catch((err) => { proxy.$Myfun.forToast(layer.value, 'open', err) })
  // ----
  if (resData && resData.success) await callWxPay(resData.datainfo)
}
/* global WeixinJSBridge */
// --吊起微信支付--
const callWxPay = (payinfo) => {
  if (WeixinJSBridge === undefined) {
    if (document.addEventListener) {
      document.addEventListener('WeixinJSBridgeReady', onBridgeReady(payinfo), false)
    } else if (document.attachEvent) {
      document.attachEvent('WeixinJSBridgeReady', onBridgeReady(payinfo))
      document.attachEvent('onWeixinJSBridgeReady', onBridgeReady(payinfo))
    }
  } else { onBridgeReady(payinfo) }
}
const onBridgeReady = async (payinfo) => {
  await WeixinJSBridge.invoke(
    'getBrandWCPayRequest',
    {
      appId: payinfo.appId,
      timeStamp: payinfo.timeStamp,
      nonceStr: payinfo.nonceStr,
      package: payinfo.package,
      signType: payinfo.signType,
      paySign: payinfo.paySign
    },
    async function (res) {
      if (String(res.err_msg) === 'get_brand_wcpay_request:ok') {
        await getAuditFun()
        proxy.$Myfun.forToast(layer.value, 'open', '微信支付成功', () => {
          if (forExtend && forExtend.name) {
            proxy.$Myfun.openPage(proxy, 'replace', forExtend.name, forExtend.opts)
          } else {
            proxy.$router.back()
          }
        })
        return false
      }
      // ----
      if (String(res.err_msg) === 'get_brand_wcpay_request:cancel') {
        proxy.$Myfun.forToast(layer.value, 'open', '你已取消支付', () => { proxy.$router.back() })
        return false
      }
      // ----
      proxy.$Myfun.forToast(layer.value, 'open', '请在手机端微信支付！！！', () => { proxy.$router.back() })
    }
  )
}
// ----
const getAuditFun = async () => {
  if (Number(Object.keys(logUser).length) > 0) {
    let typeIndex = 0
    const isTypeInfo = deadline.some((item, index) => {
      if (String(item.id) === String(forToPay.payType)) {
        typeIndex = index
        return true
      }
    })
    if (isTypeInfo) {
      const isTimeInfo = deadline[typeIndex].info.some((item, index) => {
        if (String(item.id) === String(forToPay.payId)) {
          if (forToPay.payCount) item.count = forToPay.payCount
          if (forToPay.payIntend) item.intend = forToPay.payIntend
          item.starttime = proxy.$Myfun.getToday()
          if (Number(power) === 3) {
            item.endtime = proxy.$Myfun.getNewDate({date: item.endtime, num: forDays})
          } else {
            item.endtime = proxy.$Myfun.getNewDate({num: forDays})
          }
          return true
        }
      })
      if (!isTimeInfo) {
        deadline[typeIndex].info.push({
          id: forToPay.payId,
          count: forToPay.payCount || 0,
          intend: forToPay.payIntend || [],
          starttime: proxy.$Myfun.getToday(),
          endtime: proxy.$Myfun.getNewDate({num: forDays})
        })
      }
    } else {
      deadline.push({
        id: forToPay.payType,
        info: [{
          id: forToPay.payId,
          count: forToPay.payCount || 0,
          intend: forToPay.payIntend || [],
          starttime: proxy.$Myfun.getToday(),
          endtime: proxy.$Myfun.getNewDate({num: forDays})
        }]
      })
    }
    const forLineData = JSON.stringify(deadline)
    // ----
    const forData = {
      topupze: forLineData,
      // ----
      config_id: userInfo.config_id,
      openid: userInfo.openid
    }
    if (forToPay.payAttr) forData[forToPay.payAttr] = trueNum
    await proxy.$http.patch('dealer/update?id=' + logUser.id, forData).then((curRes) => {
      proxy.$Store.set('logUser', curRes)
    }).catch((err) => { proxy.$Myfun.forToast(layer.value, 'open', err) })
  }
  return false
}

/* ---- */
onMounted(() => {
  getCurrencyInfo()
})
</script>

<template>
  <div>
    <div class="xw-section" v-if="user.logo || user.title">
      <div class="CLUB-box xw-middle-abs xw-flex xw-flex-align xw-flex-column">
        <div class="CLUB-logo" v-if="user.logo"><img :src="user.logo"/></div>
        <div class="CLUB-title" v-if="user.title">{{user.title}}</div>
      </div>
    </div>
    <layer-view ref="layer"/>
  </div>
</template>

<style scoped>
/* ---- */
.CLUB-box { padding: 0 0 30rem; text-align: center; }
.CLUB-logo { width: 10rem; }
.CLUB-logo img { width: 100%; }
.CLUB-title { margin: 2rem 0 0; font-size: 1.8rem; word-break: keep-all; white-space: nowrap; }
</style>
